package com.ytktt.study.week7.task6.snowflake;

/**
 * 雪花算法
 *
 * @author ytk
 */
public class Snowflake {

    private final long workerId;
    private final long dataCenterId;

    private final long twepoch = 1288834974657L;

    private long sequence = 0L;
    private long lastTimestamp = 1L;

    private final long workerIdBits = 5L;
    private final long dataCenterIdBits = 5L;
    private final long sequenceBits = 12L;
    private final long maxSequence = ~(-1L << this.sequenceBits);

    private final long workerIdShift = this.sequenceBits;
    private final long dataCenterIdShift = this.workerIdShift + this.workerIdBits;
    private final long timestampShift = this.dataCenterIdShift + this.dataCenterIdBits;

    public Snowflake(long workerId, long dataCenterId) {
        if (workerId > ~(-1L << this.workerIdBits) || workerId < 0 ||
                dataCenterId > ~(-1L << this.dataCenterIdBits) || dataCenterId < 0) {
            throw new IllegalArgumentException("invalid workerId/dataCenterId");
        }

        this.workerId = workerId;
        this.dataCenterId = dataCenterId;
    }

    public synchronized long nextId() {
        long timestamp = System.currentTimeMillis();
        if (timestamp < this.lastTimestamp) {
            throw new RuntimeException("时钟回调");
        }

        if (this.lastTimestamp == timestamp) {
            // 如果自增到最大后，回到0
            this.sequence = (this.sequence + 1) & this.maxSequence;
            // 如果到sequence == 0说明序列号满了 去偷下一个时间戳的
            if (sequence == 0) {
                timestamp = this.nextMills(this.lastTimestamp);
            }
        } else {
            this.sequence = 0;
        }
        this.lastTimestamp = timestamp;

        return ((timestamp - this.twepoch) << this.timestampShift) | (this.dataCenterId << this.dataCenterIdShift) |
                (this.workerId << this.workerIdShift) | this.sequence;
    }

    private long nextMills(long lastTimestamp) {
        long timestamp = System.currentTimeMillis();
        // 如果当前生成的时间戳 <= 上一次生成id的时间戳，就重新生成时间戳，即确保新生成的时间戳大于上一次生成id的时间戳
        while (timestamp <= lastTimestamp) {
            timestamp = System.currentTimeMillis();
        }
        return timestamp;
    }

}
